<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Attention;
use app\common\model\Blacklist;
use app\common\model\Config;
use app\common\model\FamilyTree;
use app\common\model\Friend;
use app\common\model\Gift;
use app\common\model\GiveLog;
use app\common\model\Vote;
use think\Db;
use think\Exception;
use app\common\model\User;

class Hiscore extends Api{
    //protected $noNeedLogin = ['editPwd'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 主页信息
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info(){
        $fId = request()->post('f_id');
        $userId = request()->post('user_id');
        if(empty($fId) && empty($userId)){
            $this->error('参数错误');
        }

        if(!empty($userId)){
            $fId = FamilyTree::where('user_id',$userId)->value('id');
        }
        $family = FamilyTree::with('user')->where('id',$fId)->find();
        if(empty($family)){
            $this->error('系统错误');
        }
        if(!empty($family->user)){
            $family->user->age = birthday($family->user->birthday);
            $family->user->is_friend = Friend::where('user_id',$this->auth->id)->where('friend_id',$family->user->id)->count();
            $family->user->is_blacklist = Blacklist::where('user_id',$this->auth->id)->where('to_user_id',$family->user->id)->count();
            $family->user->follow_count = Attention::where('att_user_id',$family->user->id)->count();
            $family->user->dynamic_count = \app\common\model\Dynamic::where('user_id',$family->user->id)->where('status',1)->count();
        }else{
            $family->age = birthday($family->start_time);
        }
        $family->child_count = FamilyTree::getChildCount($family['id']);
        //$familyId2 = FamilyTree::where('user_id',$this->auth->id)->value('family_id');
        //if($family['family_id'] != $familyId2){
        //    $family->tjz = 0;
        //}else{
        //    $family->tjz = 1;
        //}
        $this->success('请求成功',$family);
    }

    /**
     * 礼物列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function giftList(){
        $type = request()->post('type',1); // 1=礼物,2=祭祀
        $list = Gift::where('types',$type)->select();
        $this->success('请求成功',$list);
    }

    /**
     * 赠送礼物
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public function give(){
        $giftId = request()->post('gift_id');
        $num = request()->post('num');
        $user_id = request()->post('user_id',0);
        if(empty($giftId) || empty($num) || $num < 1){
            $this->error('参数错误');
        }
        $count = User::where('id',$user_id)->count();
        //if($count < 1){
        //    $this->error('参数错误!!');
        //}
        $giftInfo = Gift::get($giftId);
        if(empty($giftInfo)){
            $this->error('参数错误!');
        }
        Db::startTrans();
        try{
            $money = $giftInfo['money'] * $num;
            $score = $giftInfo['score'] * $num;
            $to_money = $giftInfo['to_money'] * $num;
            if($this->auth->money < $money){
                throw new Exception('贡献值不足',2000);
            }
            $time = time();
            $s1 = User::setMoney($this->auth->id,'money',-$money,2010,'赠送'.$giftInfo['name'].'消耗',$this->auth->id.$time);
            $s2 = User::setMoney($this->auth->id,'score',$score,2020,'赠送'.$giftInfo['name'].'获得',$this->auth->id.$time);
            if($count > 0){
                $s3 = User::setMoney($user_id,'money',$to_money,2030,'收到'.$giftInfo['name'].'获得');
            }
            if(!$s1 || !$s2){
                throw new Exception('添加记录失败');
            }

            $result = GiveLog::create([
                'user_id'=>$this->auth->id,
                'to_user_id'=>$user_id,
                'money'=>$money,
                'score'=>$score,
                'to_money'=>$to_money,
                'num'=>$num,
                'name'=> $giftInfo['name'],
                'image'=> $giftInfo['image'],
                'remark'=> $giftInfo['remark'],
                'change_id'=>$s1['changeId'],
                'gift_id'   => $giftId
            ]);
            if(!$result){
                throw new Exception('礼物记录插入失败');
            }
            if($giftInfo['types'] == 1){
                \app\common\model\Task::complete(4,$this->auth->id);
            }else{
                \app\common\model\Task::complete(5,$this->auth->id);
            }
            Db::commit();
            $this->success('赠送成功');
        }catch(Exception $e){
            Db::rollback();
            if($e->getCode() == 1000){
                $this->error($e->getMessage());
            }elseif($e->getCode() == 2000){
                $this->error($e->getMessage(),'','10');
            }else{
                write_log($e->getMessage(),'礼物赠送失败');
                $this->error('赠送失败,请联系管理员!');
            }
        }
    }


    /**
     * 赠送礼物
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public function autoGive(){
        $giftId = request()->post('gift_id');
        $num = request()->post('num');
        $user_id = request()->post('user_id');
        if(empty($giftId) || empty($num) || empty($user_id) || $num < 1){
            $this->error('参数错误');
        }
        $count = User::where('id',$user_id)->count();
        if($count < 1){
            $this->error('参数错误!!');
        }
        $giftInfo = Gift::get($giftId);
        if(empty($giftInfo)){
            $this->error('参数错误!');
        }

        Db::startTrans();
        try{
            $count = GiveLog::where('user_id',$this->auth->id)->where('to_user_id',$user_id)->where('status',0)->lock(true)->count();
            if($count > 0){
                throw new Exception('自动送礼已开启',1000);
            }
            $money = $giftInfo['money'] * $num;
            $score = $giftInfo['score'] * $num;
            $to_money = $giftInfo['to_money'] * $num;
            if($this->auth->money < $money){
                throw new Exception('贡献值不足',2000);
            }
            $time = time();
            $s1 = User::setMoney($this->auth->id,'money',-$money,2010,'赠送'.$giftInfo['name'].'消耗',$this->auth->id.$time);
            //$s2 = User::setMoney($this->auth->id,'score',$score,2020,'赠送'.$giftInfo['name'].'获得',$this->auth->id.$time);
            //$s3 = User::setMoney($user_id,'money',$to_money,2030,'收到'.$giftInfo['name'].'获得');
            if(!$s1){
                throw new Exception('添加记录失败');
            }

            $result = GiveLog::create([
                'user_id'=>$this->auth->id,
                'to_user_id'=>$user_id,
                'money'=>$money,
                'score'=>$score,
                'to_money'=>$to_money,
                'num'=>$num,
                'name'=> $giftInfo['name'],
                'image'=> $giftInfo['image'],
                'remark'=> $giftInfo['remark'],
                'status'=>0,
                'change_id'=>$s1['changeId'],
                'gift_id'   => $giftId
            ]);
            if(!$result){
                throw new Exception('礼物记录插入失败');
            }

            Db::commit();
            $this->success('赠送成功');
        }catch(Exception $e){
            Db::rollback();
            if($e->getCode() == 1000){
                $this->error($e->getMessage());
            }elseif($e->getCode() == 2000){
                $this->error($e->getMessage(),'','10');
            }else{
                write_log($e->getMessage(),'礼物赠送失败');
                $this->error('赠送失败,请联系管理员!');
            }
        }
    }

    /**
     * 关闭自动送礼
     * @throws Exception
     *
     */
    public function closeAutoGive(){
        $user_id = request()->post('user_id');
        if(empty($user_id)){
            $this->error('参数错误');
        }
        $count = User::where('id',$user_id)->count();
        if($count < 1){
            $this->error('参数错误!!');
        }
        Db::startTrans();
        try{
            $find = GiveLog::where('user_id',$this->auth->id)->where('to_user_id',$user_id)->where('status',0)->lock(true)->find();
            if(empty($find)){
                throw new Exception('未开启自动送礼,无法关闭',1000);
            }

            $time = time();
            $s1 = User::setMoney($this->auth->id,'money',$find['money'],2040,'关闭送礼退回贡献值',$this->auth->id.$time);
            //$s2 = User::setMoney($this->auth->id,'score',$score,2020,'赠送'.$giftInfo['name'].'获得',$this->auth->id.$time);
            //$s3 = User::setMoney($user_id,'money',$to_money,2030,'收到'.$giftInfo['name'].'获得');
            if(!$s1){
                throw new Exception('添加记录失败');
            }

            $result = GiveLog::where('id',$find['id'])->update(['status'=>2]);
            if(!$result){
                throw new Exception('礼物记录插入失败');
            }

            Db::commit();
            $this->success('关闭成功');
        }catch(Exception $e){
            Db::rollback();
            if($e->getCode() == 1000){
                $this->error($e->getMessage());
            }else{
                write_log($e->getMessage(),'礼物关闭失败');
                $this->error('关闭失败,请联系管理员!');
            }
        }
    }

    /**
     * 打赏
     * @throws Exception
     */
    public function vote(){
        $user_id = request()->post('user_id');
        $num = request()->post('num');
        if(empty($num) || empty($user_id) || $num < 1){
            $this->error('参数错误');
        }
        if($this->auth->id == $user_id){
            $this->error('不能给自己打赏哦');
        }
        $count = User::where('id',$user_id)->count();
        if($count < 1){
            $this->error('参数错误!!');
        }
        $money = Config::getValue('money','vote');
        if($money*$num > $this->auth->money){
            $this->error('贡献值不足');
        }
        $s1 = User::setMoney($this->auth->id,'money',-($money*$num),'3000','打赏消耗贡献值');
        if($s1){
            Vote::create([
                'user_id'   => $this->auth->id,
                'to_user_id'=> $user_id,
                'amount'    => $num
            ]);
            User::where('id',$user_id)->setInc('reward',$num);
            $this->success('打赏成功');
        }
        $this->error('打赏失败,请联系管理员');
    }
}